package com.colis.quartz.component;

import com.alibaba.fastjson.JSON;
import com.colis.quartz.common.constant.QuartzConstants;
import com.colis.quartz.module.sms.QuartzTask;
import com.colis.quartz.module.sms.QuartzTaskLog;
import com.colis.quartz.provider.sms.mapper.QuartzTaskLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.Executor;

/**
 * <p> 描述： </p>
 *
 * @author wlp
 * @version 1.0.0
 * @date 2022/1/13 15:55
 */
@Slf4j
@Component
public class MyQuartzJob extends QuartzJobBean {

    @Resource
    private QuartzTaskLogMapper quartzTaskLogMapper;

    @Resource(name = "taskExecutor")
    Executor executor;

    @Override
    public void executeInternal(JobExecutionContext context) {
        QuartzTask quartzTask = (QuartzTask) context.getMergedJobDataMap().get(QuartzConstants.QUARTZ_JOB_MAP_KEY);
        before();
        executor.execute(() -> run(quartzTask));
        after();
    }

    void before() {
        log.info("定时任务开始执行！");
    }

    void after() {
        log.info("定时任务执行完成！");
    }

    private void run(QuartzTask quartzTask) {
        //任务开始时间
        long startTime = System.currentTimeMillis();
        QuartzTaskLog quartzTaskLog = new QuartzTaskLog()
                .setQuartzId(quartzTask.getId())
                .setTargetBean(quartzTask.getTargetBean())
                .setTargetMethod(quartzTask.getTargetMethod())
                .setParams(quartzTask.getParams())
                .setQuartzName("执行定时任务【" + quartzTask.getQuartzName() + "】")
                .setQuartzStatus(0);
        try {
            quartzTaskLog.setCreateTime(LocalDateTime.now());
            log.info("开始运行" + quartzTask.getQuartzName());
            new MyQuartzSchedule().setQuartzTask(quartzTask).run();
            long times = System.currentTimeMillis() - startTime;
            quartzTaskLog.setExecutionTime(times);
        } catch (Exception e) {
            log.error("任务执行失败，任务ID：" + quartzTask.getId(), e);
            long times = System.currentTimeMillis() - startTime;
            quartzTaskLog.setExecutionTime(times);
            quartzTaskLog.setErrorInfo("任务执行完毕，任务ID：" + quartzTask.getId() + "， 总共耗时：" + times + "毫秒");
            quartzTaskLog.setQuartzStatus(1);
            quartzTaskLog.setErrorInfo("任务执行失败，任务ID：" + quartzTask.getId() + "===>>" + e.getMessage());
        } finally {
            quartzTaskLogMapper.saveAndFlush(quartzTaskLog);
        }
    }
}
